#!/usr/bin/env python

import orange
import scipy
import utils

""" Wrapper autour de la librairie Orange (KNN) """
class KNN:
    
    """Get a KNN object to calculate the nearest neighbours"""
    def __init__(self, K, matrix2, allWords):
        self.retraceWords = matrix2.retraceWords
        self.allWords = allWords

        # Chargement des donnees
        self.domain = utils.load('rickDomain2.ser')
        matrix = utils.load('rickMatrix.ser')
        trainingSet = orange.ExampleTable(self.domain, matrix.toarray())

        self.nbWords = matrix.shape[1]

        # Donner le training set a Orange
        self.knn = orange.kNNLearner(trainingSet, k=K)
        
        del matrix
        del trainingSet
        

    def classify(self, words):
        # Preparer words pour etre un bon testdata
        testdata = scipy.sparse.lil_matrix((1, self.nbWords))
        for word, occurence in words.iteritems():
            if word in self.allWords.bag:
                globalIndex = self.allWords.bag[word][0]
                if globalIndex in self.retraceWords:
                    realIndex = self.retraceWords[globalIndex]
                    testdata[0, realIndex] = occurence

        # Envoyer testdata a Orange
        testSet = orange.ExampleTable(self.domain, testdata.toarray())
        return self.knn(testSet[0])
        

    def destroy(self):
        self.flann.delete_index()

#import learning
#allWords = utils.load('allwords.ser')
#knn = KNN(allWords)
#cat, words = learning.getWords('D:/U/S6/AI/Projet/Part1/awards_1994/awd_1994_00', 'a9400001.txt')


#from RickTree import RickTree
#cats = utils.load('categories.ser')
#cls = utils.load('cls.ser')

#t = RickTree()


# idCat = cats.bag['']
# idClus = cls.cat2clus[idCat]

